<template>
	<view class="form-container">
		<!-- 店铺信息 -->
		<view class="store-info">
			<view class="store-row">
				<text class="store-icon">🏪</text>
				<text class="store-name">涮涮滨绎18.9自助旋转小火锅农大店</text>
			</view>
			<view class="store-row">
				<text class="store-icon">📍</text>
				<text class="store-address">黑龙江省哈尔滨市香坊区木材街 89号</text>
			</view>
		</view>

		<!-- 检查项目列表 -->
		<scroll-view scroll-y class="check-list">
			<!-- 调料台 -->
			<view class="check-section">
				<view class="section-title">调料台</view>
				<view class="upload-area" @click="handleUpload('seasoning')" v-if="!formData.seasoningImg">
					<view class="upload-placeholder">
						<text class="upload-icon">+</text>
						<text class="upload-text">视频图片</text>
					</view>
				</view>
				<view class="preview-area" v-else>
					<image :src="tempFilePaths.seasoningImg ? tempFilePaths.seasoningImg : `https://rsl-plus.oss-rg-china-mainland.aliyuncs.com/${formData.seasoningImg}`" mode="aspectFill" class="preview-image"/>
					<view class="preview-delete" @click="handleDelete('seasoning')">×</view>
				</view>
			</view>

			<!-- 员工服装 -->
			<view class="check-section">
				<view class="section-title">员工服装</view>
				<view class="upload-area" @click="handleUpload('uniform')" v-if="!formData.uniformImg">
					<view class="upload-placeholder">
						<text class="upload-icon">+</text>
						<text class="upload-text">视频图片</text>
					</view>
				</view>
				<view class="preview-area" v-else>
					<image :src="tempFilePaths.uniformImg ? tempFilePaths.uniformImg : `https://rsl-plus.oss-rg-china-mainland.aliyuncs.com/${formData.uniformImg}`" mode="aspectFill" class="preview-image"/>
					<view class="preview-delete" @click="handleDelete('uniform')">×</view>
				</view>
			</view>

			<!-- 店铺环境 -->
			<view class="check-section">
				<view class="section-title">店铺环境</view>
				<view class="upload-area" @click="handleUpload('environment')" v-if="!formData.environmentImg">
					<view class="upload-placeholder">
						<text class="upload-icon">+</text>
						<text class="upload-text">视频图片</text>
					</view>
				</view>
				<view class="preview-area" v-else>
					<image :src="tempFilePaths.environmentImg ? tempFilePaths.environmentImg : `https://rsl-plus.oss-rg-china-mainland.aliyuncs.com/${formData.environmentImg}`" mode="aspectFill" class="preview-image"/>
					<view class="preview-delete" @click="handleDelete('environment')">×</view>
				</view>
			</view>

			<!-- 菜品区 -->
			<view class="check-section">
				<view class="section-title">菜品区</view>
				<view class="upload-area" @click="handleUpload('food')" v-if="!formData.foodImg">
					<view class="upload-placeholder">
						<text class="upload-icon">+</text>
						<text class="upload-text">视频图片</text>
					</view>
				</view>
				<view class="preview-area" v-else>
					<image :src="tempFilePaths.foodImg ? tempFilePaths.foodImg : `https://rsl-plus.oss-rg-china-mainland.aliyuncs.com/${formData.foodImg}`" mode="aspectFill" class="preview-image"/>
					<view class="preview-delete" @click="handleDelete('food')">×</view>
				</view>
			</view>
		</scroll-view>

		<!-- 底部提交按钮 -->
		<view class="submit-area">
			<button 
				class="submit-btn" 
				:class="{ 'submitted': isSubmitted }"
				@click="handleSubmit"
				:disabled="isSubmitted || !canSubmit"
			>
				{{ isSubmitted ? '已提交' : '提交' }}
			</button>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { selfCheckApi } from '../../utils/api'

// 获取路由参数
const routeParams = ref(null)

// 表单数据
const formData = ref({
	seasoningImg: null,
	uniformImg: null,
	environmentImg: null,
	foodImg: null
})

const tempFilePaths = ref({
	seasoningImg: '',
	uniformImg: '',
	environmentImg: '',
	foodImg: ''
})

const checkList = ref([])

// 是否已提交
const isSubmitted = ref(false)

// 当前日期
const currentDate = computed(() => {
	const date = new Date()
	return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
})


onMounted(async () => {
	// 获取路由参数 获取id来进行查找 - 根据自检编号查找图片
	const pages = getCurrentPages()
	const currentPage = pages[pages.length - 1]
	routeParams.value = currentPage.options

	const res = await selfCheckApi.getSelfCheckImage(routeParams.value.id)
	console.log(res)
	console.log(routeParams.value.id)
	checkList.value = res.data
	
	// 根据图片描述映射到对应的表单字段
	if (res.code === 200 && res.data.length > 0) {
		res.data.forEach(item => {
			switch(item.imageDescribe) {
				case '后厨环境检查':
					formData.value.seasoningImg = item.image
					break
				case '员工服装规范':
					formData.value.uniformImg = item.image
					break
				case '店铺整体环境':
					formData.value.environmentImg = item.image
					break
				case '菜品区展示效果':
					formData.value.foodImg = item.image
					break
			}
		})
		// 设置已提交状态
		isSubmitted.value = true
	}
	
	// 设置页面标题
	uni.setNavigationBarTitle({
		title: currentDate.value
	})
})

// 是否可以提交
const canSubmit = computed(() => {
	return formData.value.seasoningImg &&
		formData.value.uniformImg &&
		formData.value.environmentImg &&
		formData.value.foodImg
})

// 处理图片上传
function handleUpload(type) {
	if (isSubmitted.value) return
	
	uni.chooseImage({
		count: 1,
		success: (res) => {
			// Store the file object
			formData.value[`${type}Img`] = res.tempFiles[0]
			// Store the temp path for preview
			tempFilePaths.value[`${type}Img`] = res.tempFilePaths[0]
		}
	})
}

// 处理图片删除
function handleDelete(type) {
	if (isSubmitted.value) return
	formData.value[`${type}Img`] = null
	tempFilePaths.value[`${type}Img`] = ''
}

// 处理提交
async function handleSubmit() {
	if (!canSubmit.value || isSubmitted.value) return
	console.log(formData.value)
	try {
		// 构建图片描述数组
		const imageList = [
			{ imageDescribe: '后厨环境检查', siId: routeParams.value.id },
			{ imageDescribe: '员工服装规范', siId: routeParams.value.id },
			{ imageDescribe: '店铺整体环境', siId: routeParams.value.id },
			{ imageDescribe: '菜品区展示效果', siId: routeParams.value.id }
		];

		// 获取token
		const token = uni.getStorageSync('token');
		
		// 创建一个Promise数组来存储所有上传任务
		const uploadTasks = Object.entries(formData.value).map(([key, file], index) => {
			return new Promise((resolve, reject) => {
				if (!file || !file.path) {
					reject(new Error(`文件 ${key} 不存在`));
					return;
				}
				
				uni.uploadFile({
					url: 'http://192.168.29.125:8080/api/inspect-image/submit',
					filePath: file.path,
					name: 'files',
					header: {
						'auth': token
					},
					formData: {
						inspectImage: JSON.stringify(imageList[index])
					},
					success: (uploadRes) => {
						try {
							const data = JSON.parse(uploadRes.data);
							if (data.code === 200) {
								resolve(data);
							} else {
								reject(new Error(data.message || '上传失败'));
							}
						} catch (parseError) {
							reject(new Error('服务器响应格式错误'));
						}
					},
					fail: (error) => {
						reject(error);
					}
				});
			});
		});

		// 等待所有文件上传完成
		await Promise.all(uploadTasks);
		
		uni.showToast({
			title: '提交成功',
			icon: 'success'
		});
		
		// 上传成功后更新状态
		isSubmitted.value = true;
		// 延迟返回上一页
		setTimeout(() => {
			uni.navigateBack();
		}, 2000);
		
	} catch (error) {
		console.error('上传过程出错:', error);
		uni.showToast({
			title: error.message || '提交失败',
			icon: 'none'
		});
	}
}

</script>

<style>
.form-container {
	min-height: 100vh;
	background-color: #f5f5f5;
	display: flex;
	flex-direction: column;
}

.store-info {
	background-color: #ffffff;
	padding: 30rpx;
}

.store-row {
	display: flex;
	align-items: center;
	margin-bottom: 20rpx;
}

.store-row:last-child {
	margin-bottom: 0;
}

.store-icon {
	margin-right: 20rpx;
	font-size: 32rpx;
}

.store-name {
	font-size: 32rpx;
	font-weight: 500;
	color: #333;
}

.store-address {
	font-size: 28rpx;
	color: #666;
}

.check-list {
	flex: 1;
	padding: 30rpx;
}

.check-section {
	margin-bottom: 40rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: 500;
	color: #333;
	margin-bottom: 20rpx;
}

.upload-area {
	width: 100%;
	height: 300rpx;
	background-color: #ffffff;
	border: 2rpx dashed #ddd;
	border-radius: 12rpx;
	display: flex;
	justify-content: center;
	align-items: center;
}

.upload-placeholder {
	display: flex;
	flex-direction: column;
	align-items: center;
	color: #999;
}

.upload-icon {
	font-size: 60rpx;
	line-height: 1;
	margin-bottom: 10rpx;
}

.upload-text {
	font-size: 28rpx;
}

.preview-area {
	position: relative;
	width: 100%;
	height: 300rpx;
	border-radius: 12rpx;
	overflow: hidden;
}

.preview-image {
	width: 100%;
	height: 100%;
}

.preview-delete {
	position: absolute;
	top: 10rpx;
	right: 10rpx;
	width: 50rpx;
	height: 50rpx;
	background-color: rgba(0, 0, 0, 0.5);
	color: #ffffff;
	border-radius: 25rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	font-size: 32rpx;
}

.submit-area {
	padding: 30rpx;
	background-color: #ffffff;
}

.submit-btn {
	width: 100%;
	height: 88rpx;
	line-height: 88rpx;
	text-align: center;
	background-color: #c70209;
	color: #ffffff;
	border-radius: 44rpx;
	font-size: 32rpx;
	border: none;
}

.submit-btn.submitted {
	background-color: #67c23a;
}

.submit-btn[disabled] {
	background-color: #cccccc;
	color: #ffffff;
}
</style>
